import { Card, Button, Checkbox, Form, Input, message } from "antd";
import logo from "@/assets/logo.png";
import "./index.scss";

import { fetchLogin } from "@/stores/modules/login";
import { useDispatch } from "react-redux";
import { useNavigate } from "react-router-dom";
const Login = () => {
  const [form] = Form.useForm();
  const dispatch = useDispatch();
  const navigate = useNavigate();
  const checkMobile = function (rule, value) {
    if (!value) {
      return Promise.reject(new Error("请输入手机号"));
    }
    const reg = /^1[3|7|5|][0-9]{9}$/;
    if (!reg.test(value)) {
      return Promise.reject(new Error("手机号格式错误"));
    }
    return Promise.resolve();
  };
  const onFinish = async function (val) {
    await dispatch(
      fetchLogin({
        mobile: val.mobile,
        code: val.code,
      })
    );
    message.success("登录成功");
    navigate("/");
  };

  return (
    <div className="login">
      <Card className="login-container">
        <img className="login-logo" src={logo} alt="" />
        {/* 登录表单 */}
        <Form
          form={form}
          validateTrigger="onBlur"
          initialValues={{
            mobile: "13218919256",
            code: "246810",
            isChecked: false,
          }}
          onFinish={(values) => {
            onFinish(values);
          }}
        >
          <Form.Item
            name="mobile"
            rules={[
              {
                validator: checkMobile,
              },
            ]}
          >
            <Input size="large" placeholder="请输入手机号" />
          </Form.Item>
          <Form.Item
            name="code"
            rules={[
              {
                required: true,
                message: "Please input your code!",
              },
              {
                pattern: /^[0-9]{6}$/,
                message: "请输入6位验证码",
              },
            ]}
          >
            <Input size="large" placeholder="请输入验证码" />
          </Form.Item>
          <Form.Item
            name="isChecked"
            valuePropName="checked"
            rules={[
              {
                validator: (_, value) =>
                  value
                    ? Promise.resolve()
                    : Promise.reject(new Error("请勾选协议")),
              },
            ]}
          >
            <Checkbox className="login-checkbox-label">
              我已阅读并同意「用户协议」和「隐私条款」
            </Checkbox>
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit" size="large" block>
              登录
            </Button>
          </Form.Item>
        </Form>
      </Card>
    </div>
  );
};

export default Login;
